namespace EyeOpen.Logging
{
	using System;
	using System.Collections.Generic;
	using System.Linq;

	public class DictionaryDependencyResolver : 
		IDependencyResolver
	{
		private readonly IDictionary<Type, List<object>> typeDictionary =
			new Dictionary<Type, List<object>>();

		public T Resolve<T>()
		{
			var type = typeof(T);

			if (typeDictionary.ContainsKey(type))
			{
				return
					(T)typeDictionary[type].Single();
			}

			return
				default(T);
		}

		public void Register(object obj)
		{
			RegisterInstance(obj.GetType(), obj);
		}

		public void Register<T>(object obj)
		{
			this.RegisterInstance(typeof(T), obj);
		}

		public void Remove(object obj)
		{
			RemoveInstance(obj.GetType(), obj);
		}

		public void Remove<T>(object obj)
		{
			RemoveInstance(typeof(T), obj);
		}

		private void RemoveInstance(Type type, object obj)
		{
			var objectList = 
				this.typeDictionary[type];

			objectList.Remove(obj);

			if (objectList.Count == 0)
			{
				this.typeDictionary.Remove(type);
			}
		}

		private void RegisterInstance(Type type, object obj)
		{
			List<object> objectList;

			if (!this.typeDictionary.ContainsKey(type))
			{
				objectList = new List<object>();
				this.typeDictionary.Add(type, objectList);
			}
			else
			{
				objectList = this.typeDictionary[type];
			}

			objectList.Add(obj);
		}
	}
}